package com.thinkcube.edutainment.fragment;

import java.util.List;

import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.Trace;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.rest.RestService;
import org.androidannotations.annotations.sharedpreferences.Pref;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.thinkcube.edutainment.EdutainmentConstant;
import com.thinkcube.edutainment.R;
import com.thinkcube.edutainment.ReachabilityTest;
import com.thinkcube.edutainment.adapters.CourseAdapater;
import com.thinkcube.edutainment.client.CourseClient;
import com.thinkcube.edutainment.client.UserClient;
import com.thinkcube.edutainment.domain.OAuth;
import com.thinkcube.edutainment.domain.data.CourseData;
import com.thinkcube.edutainment.domain.dto.CourseDto;
import com.thinkcube.edutainment.domain.dto.OAuthDto;
import com.thinkcube.edutainment.service.SPreferences_;

/**
 * A fragment representing a single Search detail screen. This fragment is
 * either contained in a {@link SearchListActivity} in two-pane mode (on
 * tablets) or a {@link SearchDetailActivity} on handsets.
 */

@EFragment
public class SearchDetailFragment extends Fragment {

	@ViewById(R.id.listview)
	GridView listview;

	@ViewById(R.id.progressBar)
	ProgressBar progress;
	
	@ViewById(R.id.not_found)
	TextView notFound;

	private EditText searchText;

	Activity activity;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_search_detail,
				container, false);
		searchText = ((EditText) rootView.findViewById(R.id.search_detail));
		activity = getActivity();

//		System.out.println("KEY " + getArguments().getString("filter"));
//		System.out.println("Search " + getArguments().containsKey("searchText"));
		
		
		if (getArguments().containsKey("filter")
				&& getArguments().getString("filter") != null) {
			search(getArguments().getString("filter"));
		}

		if (getArguments().containsKey("searchText")  ) {
			
			if(getArguments().getString("searchText")!=null){
			searchText.setText(getArguments().getString("searchText"));
			search(searchText.getText().toString(), null);
			}
			
			if(getArguments().getString("searchText").isEmpty()){
				search("latest");
			}
			
		}
		
		if (getArguments().containsKey("category_id") && getArguments().getString("category_id") !=null) {
			
			search(null, getArguments().getString("category_id"));
		}

		searchText
				.setOnEditorActionListener(new TextView.OnEditorActionListener() {
					@Override
					public boolean onEditorAction(TextView v, int actionId,
							KeyEvent event) {
						if (actionId == EditorInfo.IME_ACTION_SEARCH) {

							progress.setVisibility(View.VISIBLE);

							search(searchText.getText().toString(), null);
							listview.setAdapter(null);

							if (getActivity().getCurrentFocus() != null
									&& getActivity().getCurrentFocus() instanceof EditText) {
								
								InputMethodManager imm = (InputMethodManager) getActivity()
										.getSystemService(
												Context.INPUT_METHOD_SERVICE);
								imm.hideSoftInputFromWindow(
										searchText.getWindowToken(), 0);
							}
							
							return true;
						}
						return false;
					}
				});

		return rootView;
	}

	@RestService
	CourseClient courseClient;
	@Bean
	CourseDto courseDto;

	@Pref
	SPreferences_ pref;

	
	@UiThread
	void showMessge(final String msg) {
		Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
	}

	@Bean
	OAuthDto oAuthDto;

	@RestService
	UserClient userClient;

	@Trace
	// @AfterViews
	@Background
	void search(final String term, final String cat) {
		oAuthDto.setAppId(EdutainmentConstant.APP_ID);
		oAuthDto.setAppSecret(EdutainmentConstant.APP_SCRET);

		new ReachabilityTest(getActivity(), new ReachabilityTest.Callback() {

			@Override
			public void onReachabilityTestPassed() {

				try {
					setTokenUi(term, cat, userClient.getRequestToken(oAuthDto
							.getMultiValuedMap()));
				} catch (Exception e) {

					// showMessge(e.getLocalizedMessage());
				}
			}

			@Override
			public void onReachabilityTestFailed() {

				showMessge("Not connected ");
			}
		});
	}

	@Background
	void search(final String filter) {
		oAuthDto.setAppId(EdutainmentConstant.APP_ID);
		oAuthDto.setAppSecret(EdutainmentConstant.APP_SCRET);

		new ReachabilityTest(getActivity(), new ReachabilityTest.Callback() {

			@Override
			public void onReachabilityTestPassed() {

				try {
					searcht(filter, userClient.getRequestToken(oAuthDto
							.getMultiValuedMap()));
				} catch (Exception e) {

					// showMessge(e.getLocalizedMessage());
				}
			}

			@Override
			public void onReachabilityTestFailed() {

				showMessge("Not connected ");
			}
		});
	}

	@Background
	void searcht(String filter, OAuth requestToken) {

		courseDto.setAuthToken(requestToken.getoAuth().getToken());
		courseDto.setUserId(pref.getId().get());
		//System.out.println("filter" + filter);
		if (filter.equals("Featured")) {

			courseDto.setFilterBy("featured");
		} else if (filter.equals("Top Rated")) {
			courseDto.setFilterBy("top_rated");
		} else if (filter.equals("Latest")) {
			courseDto.setFilterBy("latest");
		} else if (filter.equals("Recommended")) {
			courseDto.setFilterBy("recommended");
		}

		new ReachabilityTest(getActivity(), new ReachabilityTest.Callback() {

			@Override
			public void onReachabilityTestPassed() {

				try {
					placeListUI(courseClient.getFiltercourses(
							courseDto.getMultiValuedMap()).getCourseList());
				} catch (Exception e) {

					// showMessge(e.getLocalizedMessage());
				}
			}

			@Override
			public void onReachabilityTestFailed() {

				showMessge("Not connected ");
			}
		});

	}

	void setTokenUi(String term, String cat, OAuth requestToken) {

		searcht(term, cat, requestToken);
	}

	@Trace
	@Background
	void searcht(String term, String cat, OAuth requestToken) {

		courseDto.setAuthToken(requestToken.getoAuth().getToken());
		courseDto.setUserId(pref.getId().get());

		if (term != null) {

			courseDto.setTerm(term);

			new ReachabilityTest(getActivity(),
					new ReachabilityTest.Callback() {

						@Override
						public void onReachabilityTestPassed() {

							try {
								placeListUI(courseClient.getSearchSourses(
										courseDto.getMultiValuedMap())
										.getCourseList());
							} catch (Exception e) {

								// showMessge(e.getLocalizedMessage());
							}
						}

						@Override
						public void onReachabilityTestFailed() {

							showMessge("Not connected ");
						}
					});
		} else if (cat != null) {

			courseDto.setCategoryId(cat);

			new ReachabilityTest(getActivity(),
					new ReachabilityTest.Callback() {

						@Override
						public void onReachabilityTestPassed() {

							try {
								List<CourseData> list = courseClient
										.getGetCoursesByCat(
												courseDto.getMultiValuedMap())
										.getCourseList();
								placeListUI(list);
							} catch (Exception e) {

								// showMessge(e.getLocalizedMessage());
								progress.setVisibility(View.GONE);
							}
						}

						@Override
						public void onReachabilityTestFailed() {

							showMessge("Not connected ");
							progress.setVisibility(View.GONE);
						}
					});

		}
		
	}

	@UiThread
	void placeListUI(final List<CourseData> courseList) {

		progress.setVisibility(View.GONE);
		
		if((courseList!=null)&&(courseList.size()!=0))
		{
				listview.setAdapter(new CourseAdapater(getActivity(), courseList));
		
				listview.setOnItemClickListener(new OnItemClickListener() {
		
					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int position, long arg3) {
		
						Bundle bundle = new Bundle();
		
						CourseViewFragment coursview = new CourseViewFragment_();
						bundle.putParcelable("course", courseList.get(position));
						coursview.setArguments(bundle);
						final FragmentTransaction fragmentTransaction = getFragmentManager()
								.beginTransaction();
						fragmentTransaction.replace(R.id.myfragment, coursview,
								"newfrag");
						fragmentTransaction.addToBackStack(null);
		
						// Commit the transaction
						fragmentTransaction.commit();
					}
				});
		}
		else if(courseList==null)
		{
			notFound.setVisibility(View.VISIBLE);
		}
	}

}
